<?php if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/12/9
 * Time: 15:33
 */
//header("Content-type: text/html; charset=utf-8");
class Filemanage extends MY_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('file_model');


        /*
        //这是设置权限的配置
        $this->load->model('users_model');
        $arr = $this->users_model->GetPermissionByRoleId(1);
        print_r(json_decode($arr[0]['permission']));
        $segArray = $this->uri->segment_array();
        //获取当前权限键,移除index
        if($segArray[4]=='index'){
            $segArray[4]='';
        }
        $permissionKey=$segArray[3].'_'.$segArray[4];
        echo("permissionKey:".$permissionKey);
        */
    }

    public function index()
    {   
    
    //echo('cc');
        //print_r(ini_get_all());
        $title = $_GET['keys'];
        $type = $_GET['tid'];
        if (!empty($title)) {
            $ar = array('title' => $title);
        } else {
            $ar = null;
        }
        if ($type == 0) {
            $artp = array(1, 2, 3, 4);
        } else {
            $artp = array($type);
        }

        $this->listfile('typeid', $artp, $ar, 1);

    }

    /**
     * 文件上传函数
     */
    public function uploadfiles()
    {
        $action = $_POST['action'];
        $title = $_POST['title'];
        $type = $_POST['type'];//类型id


        $userinfo = $this->users;
        $add_user = serialize($userinfo);//上传的用户信息
        $add_time = time();//获取当前的时间

        $user_id = $userinfo['id'];
        $objtype = $this->file_model->getTypeNameByTypeId($type);
        $typename = $objtype[0]->name;//获取typename
        if ($action == "submit") {
            $uploaddir = './resource/uploadfiles/file/uploadify/' . date("Y") . '/' . date("m") . '/';//上传的文件保存在当前目录,按照年/月的格式保存


            $fileretrun = uploadfile($_FILES['fileField'], $uploaddir, '', 19 * 1048576);
            if ($fileretrun == 2) {
                js_goto('', '文件大于19M！！！不能上传', 1);
            } else if ($fileretrun == 3) {
                js_goto('', '上传错误', 1);
            } else {
                $array = array('filename' => str_replace(base_url(), './', $fileretrun), 'title' => $title, 'typeid' => $type, 'typename' => $typename, 'add_user' => $add_user, 'add_time' => $add_time, 'user_id' => $user_id);
                $this->file_model->addfiles($array);
            }
            redirect($_SERVER['HTTP_REFERER']);//跳回上一个页面

            //$this->listfile(array() , 1);
        }
    }

    /**
     * 显示所有文件信息
     */
    public function listfile($filed, $where = array(), $like = array(), $page = '')
    {


        $param = '';
        if (isset($_GET['keys']) && isset($_GET['tid'])) {
            $param = '&keys=' . trim($_GET['keys']) . '&tid=' . trim($_GET['tid']);
        }
        $page = intval($_GET['page']) == 0 ? 1 : intval($_GET['page']);
        $this->load->library('pagination');
        $total = $this->file_model->countFileByTypeIdAndKey($where, $like);
        $per_page = (isset($_COOKIE['file_per'])) ? intval($_COOKIE['file_per']) : 10;//判断cookie是否存在，如果存在则按照cookie保存的数据处理，否则，显示10条/页
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('files/Filemanage/?' . $param);
        $config['total_rows'] = $total;
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $config['per_page'] = $per_page;
        $this->pagination->initialize($config);
        $data['total'] = $total;//返回总条数
        $data['cur_page'] = empty($page) ? 1 : $page;//当前页数
        //以下处理当前显示的代码
        $show_cur = "0";
        if ($total == 0) //首先总条数需要大于0
        {
            $show_cur = " 0 ";
        } elseif ($total < $per_page)//如果总条数小于分页的条数
        {
            $show_cur = "1 - " . $total;
        } elseif (($page == ceil($total / $per_page))) //尾页
        {
            $show_cur = (($page - 1) * $per_page + 1) . ' - ' . $total;

        } else//否则
        {
            $show_cur = (($page - 1) * $per_page + 1) . ' - ' . ($page * $per_page);

        }
        //print_r($this->uri->segment(5 , 1));
        $data['show_cur'] = $show_cur;
        $data['per_page'] = $per_page;//每页显示条数
        $data['pageshow'] = $this->pagination->create_links();
        $list = $this->file_model->initFiles($filed, $where, $like, $config['per_page'], ($page - 1) * $config['per_page']);
        foreach ($list as $k => $v) {
            $user = unserialize($v['add_user']);
            $list[$k]['account'] = $user['account'];
        }
        $data['listss'] = $list;
        $data['filetype'] = $this->file_model->filetypelistByParentid('5');
        $this->load->view('defaults/filemanege', $data);
        $this->load->view('defaults/common/footer');
    }

    /**
     * 搜索文件
     */
    public function seachfile()
    {
        $title = $_GET['keys'];
        $type = $_GET['tid'];
        if (!empty($title)) {
            $ar = array('title' => $title);
        } else {
            $ar = null;
        }
        //listfile($filed , $where = array() , $like = array() , $page = '')
        //$this->listfile('typeid' , array(1 , 2 , 3 , 4) , null , 1);
        $this->listfile("typeid", $type, $ar, null);
    }

    /**
     * 下载文件
     */
    public function downfile()
    {
        $id = $this->uri->segment(5);
	
        $data = $this->file_model->getfiles(array('id' => $id), 1, 0);
        $file_name = $data[0]['filename'];//需要下载的文件
        $file_name = iconv("utf-8", "gb2312", "$file_name");
        $file_title = iconv("utf-8", "gb2312", $data[0]['title']);

        $file_type = pathinfo($file_name, PATHINFO_EXTENSION);
        if (!file_exists($file_name)) {//判断文件是否存在
            js_goto(blang_url('files/Filemanage'), '文件不存在！', 1);
            exit(); //直接退出
        } //如果存在，继续执行下载
        $fp = fopen($file_name, "r+");//下载文件必须先要将文件打开，写入内存
        $file_size = filesize($file_name);//判断文件大小
        //返回的文件
        Header("Content-type: application/octet-stream");
        //按照字节格式返回
        Header("Accept-Ranges: bytes");
        //返回文件大小
        Header("Accept-Length: " . $file_size);
        //弹出客户端对话框，对应的文件名
        Header("Content-Disposition: attachment; filename=" . $file_title . '.' . $file_type);//重命名文件名
        //防止服务器瞬时压力增大，分段读取
        $buffer = 1024;
        while (!feof($fp)) {
            $file_data = fread($fp, $buffer);
            echo $file_data;
        }
        //关闭文件
        fclose($fp);
    }

    /**
     * 删除文件
     */
    public function deletefile()
    {
        $roleAry = array('admin', 'prezwang', 'zlj', 'lyb');
        if (!in_array($this->users['account'], $roleAry)) {
            js_goto('', '你没有权限！', '');
            // redirect(blang_url('orders/order'));
            return;
        }
        $id = $this->uri->segment(5);
        $pid = $this->uri->segment(6);
        $rs = $this->file_model->deletefiles($id);
        $rurl = '';
        switch ($pid) {
            case 5://维修文档
                $rurl = blang_url('files/Filemanage');
                break;
            case 6://流程规范
                $rurl = blang_url('files/Filemanage/process');
                break;
            case 7://合同资料
                $rurl = blang_url('files/Filemanage/contract');
                break;
            case 8://单据模板
                $rurl = blang_url('files/Filemanage/bill');
                break;
            default:
                $rurl = blang_url('files/Filemanage');
                break;
        }
        redirect($rurl);
    }

    /**
     * ajax删除文件
     */
    public function ajax_del()
    {
        $roleAry = array('admin', 'prezwang', 'zlj', 'lyb','Belle');
        if (!in_array($this->users['account'], $roleAry)) {
            die('-1');//-1是没有权限
            // redirect(blang_url('orders/order'));
            //ajax

        }
        $id = $_POST['id'];

        $rs = $this->file_model->deletefiles($id);
        die($rs);
    }

    /**
     * ajax修改文件
     */
    public function ajax_update()
    {
        $id = $this->uri->segment(5);
        $tparentid = $this->uri->segment(6);//这里是获取文件类型父类的id，用于判别哪一类
        $title = $_POST['title'];
        $type = $_POST['type'];
        $parentid = $_POST['parentid'];
        $objtype = $this->file_model->getTypeNameByTypeId($type);
        $typename = $objtype[0]->name;//获取typename

        if ($title != '' || $type != '') {
            $this->file_model->updatefiles($id, array('title' => $title, 'typeid' => $type, 'typename' => $typename));
            //用这种的方式去处理，不好，应该传递参数去前台处理，而且这样只有js代码没有标准头文件的方式也不科学
            die('<script type="text/javascript">parent.layer.msg("修改成功！");parent.location.reload(); // 父页面刷新  </script>');
        } else {
            $data['fileslist'] = $this->file_model->listfiles(array('id' => $id), 1, 0);
            $data['filetype'] = $this->file_model->filetypelistByParentid($tparentid);
            $data['parentid'] = $tparentid;
            $this->load->view('defaults/filepost_ajax', $data);
        }
    }

    /**
     * 修改文件属性
     */
    public function updatefile()
    {
        $id = $this->uri->segment(5);
        $tparentid = $this->uri->segment(6);//这里是获取文件类型父类的id，用于判别哪一类
        $title = $_POST['title'];
        $type = $_POST['type'];
        $parentid = $_POST['parentid'];
        $objtype = $this->file_model->getTypeNameByTypeId($type);
        $typename = $objtype[0]->name;//获取typename

        if ($title != '' || $type != '') {
            $this->file_model->updatefiles($id, array('title' => $title, 'typeid' => $type, 'typename' => $typename));
            //$this->listfile(array() , 1);
            $rurl = '';
            switch ($parentid) {
                case 5://维修文档
                    $rurl = blang_url('files/Filemanage');
                    break;
                case 6://流程规范
                    $rurl = blang_url('files/Filemanage/process');
                    break;
                case 7://合同资料
                    $rurl = blang_url('files/Filemanage/contract');
                    break;
                case 8://单据模板
                    $rurl = blang_url('files/Filemanage/bill');
                    break;
                default:
                    $rurl = blang_url('files/Filemanage');
                    break;
            }
            redirect($rurl);
        } else {
            $data['fileslist'] = $this->file_model->listfiles(array('id' => $id), 1, 0);
            $data['filetype'] = $this->file_model->filetypelistByParentid($tparentid);
            $data['parentid'] = $tparentid;
            $this->load->view('defaults/filepost', $data);
        }
    }


    /**
     * 显示合同列表
     */
    public function contract()
    {


        $where = array('typeid' => '7');
        $key = trim($_GET['keys']);
        $like = null;
        if (!empty($key)) {
            $like = array('title' => $key);
        }
        $param = '';
        if (isset($_GET['keys'])) {
            $param = '&keys=' . $key;
        }
        $page = intval($_GET['page']) == 0 ? 1 : intval($_GET['page']);
        is_numeric($where) ? $where = array() : $where = $where;
        $this->load->library('pagination');
        $total = $this->file_model->countFileByTypeIdAndKey("7", $like);

        $per_page = (isset($_COOKIE['cont_per'])) ? intval($_COOKIE['cont_per']) : 10;//判断cookie是否存在，如果存在则按照cookie保存的数据处理，否则，显示10条/页

        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('files/Filemanage/contract/?' . $param);
        $config['total_rows'] = $total;
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;


        $config['per_page'] = $per_page;
        $this->pagination->initialize($config);
        $data['total'] = $total;//返回总条数
        $data['cur_page'] = empty($page) ? 1 : $page;//当前页数
        //以下处理当前显示的代码
        $show_cur = "0";
        if ($total == 0) //首先总条数需要大于0
        {
            $show_cur = " 0 ";
        } elseif ($total < $per_page)//如果总条数小于分页的条数
        {
            $show_cur = "1 - " . $total;
        } elseif (($page == ceil($total / $per_page))) //尾页
        {
            $show_cur = (($page - 1) * $per_page + 1) . ' - ' . $total;

        } else//否则
        {
            $show_cur = (($page - 1) * $per_page + 1) . ' - ' . ($page * $per_page);

        }
        //print_r($this->uri->segment(5 , 1));
        $data['show_cur'] = $show_cur;
        $data['per_page'] = $per_page;//每页显示条数
        $data['pageshow'] = $this->pagination->create_links();


        $list = $this->file_model->initFiles('typeid', $where, $like, $config['per_page'], ($page - 1) * $config['per_page']);
        foreach ($list as $k => $v) {
            $user = unserialize($v['add_user']);
            $list[$k]['account'] = $user['account'];
        }
        $data['listss'] = $list;

        //$data['listss'] = $this->file_model->listfiles($where , $config['per_page'] , ($page - 1) * $config['per_page']);
        $data['filetype'] = $this->file_model->filetypelistByParentid('7');
        $this->load->view('defaults/contractmanege', $data);
        $this->load->view('defaults/common/footer');

    }


    /**
     * 显示流程规范列表
     */
    public function process()
    {
        //print_r($this->session->userdata['users']);
        //echo time();
        $where = array('typeid' => '6');
        $key = trim($_GET['keys']);
        $like = null;
        if (!empty($key)) {
            $like = array('title' => $key);
        }
        $param = '';
        if (isset($_GET['keys'])) {
            $param = '&keys=' . $key;
        }
        $page = intval($_GET['page']) == 0 ? 1 : intval($_GET['page']);
        is_numeric($where) ? $where = array() : $where = $where;
        $this->load->library('pagination');
        $total = $this->file_model->countFileByTypeIdAndKey("6", $like);
        $per_page = (isset($_COOKIE['process_per'])) ? intval($_COOKIE['process_per']) : 10;//判断cookie是否存在，如果存在则按照cookie保存的数据处理，否则，显示10条/页
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('files/Filemanage/process/?' . $param);
        $config['total_rows'] = $total;
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;


        $config['per_page'] = $per_page;
        $this->pagination->initialize($config);
        $data['total'] = $total;//返回总条数
        $data['cur_page'] = empty($page) ? 1 : $page;//当前页数
        //以下处理当前显示的代码
        $show_cur = "0";
        if ($total == 0) //首先总条数需要大于0
        {
            $show_cur = " 0 ";
        } elseif ($total < $per_page)//如果总条数小于分页的条数
        {
            $show_cur = "1 - " . $total;
        } elseif (($page == ceil($total / $per_page))) //尾页
        {
            $show_cur = (($page - 1) * $per_page + 1) . ' - ' . $total;

        } else//否则
        {
            $show_cur = (($page - 1) * $per_page + 1) . ' - ' . ($page * $per_page);

        }
        //print_r($this->uri->segment(5 , 1));
        $data['show_cur'] = $show_cur;
        $data['per_page'] = $per_page;//每页显示条数
        $data['pageshow'] = $this->pagination->create_links();
        $list = $this->file_model->initFiles('typeid', $where, $like, $config['per_page'], ($page - 1) * $config['per_page']);
        foreach ($list as $k => $v) {
            $user = unserialize($v['add_user']);
            $list[$k]['account'] = $user['account'];
        }
        $data['listss'] = $list;
        $data['filetype'] = $this->file_model->filetypelistByParentid('7');
        $this->load->view('defaults/processmanege', $data);
        $this->load->view('defaults/common/footer');

    }

    /**
     * 显示单据模板列表
     */
    public function bill()
    {
        //print_r($this->session->userdata['users']);
        //echo time();
        $where = array('typeid' => '8');
        $key = trim($_GET['keys']);
        $like = null;
        if (!empty($key)) {
            $like = array('title' => $key);
        }
        $param = '';
        if (isset($_GET['keys'])) {
            $param = '&keys=' . $key;
        }
        $page = intval($_GET['page']) == 0 ? 1 : intval($_GET['page']);

        is_numeric($where) ? $where = array() : $where = $where;
        $this->load->library('pagination');

        $total = $this->file_model->countFileByTypeIdAndKey("8", $like);
        $per_page = (isset($_COOKIE['bill_per'])) ? intval($_COOKIE['bill_per']) : 10;//判断cookie是否存在，如果存在则按照cookie保存的数据处理，否则，显示10条/页
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('files/Filemanage/bill/?' . $param);
        $config['total_rows'] = $total;
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;


        $config['per_page'] = $per_page;
        $this->pagination->initialize($config);
        $data['total'] = $total;//返回总条数
        $data['cur_page'] = empty($page) ? 1 : $page;//当前页数
        //以下处理当前显示的代码
        $show_cur = "0";
        if ($total == 0) //首先总条数需要大于0
        {
            $show_cur = " 0 ";
        } elseif ($total < $per_page)//如果总条数小于分页的条数
        {
            $show_cur = "1 - " . $total;
        } elseif (($page == ceil($total / $per_page))) //尾页
        {
            $show_cur = (($page - 1) * $per_page + 1) . ' - ' . $total;

        } else//否则
        {
            $show_cur = (($page - 1) * $per_page + 1) . ' - ' . ($page * $per_page);

        }
        //print_r($this->uri->segment(5 , 1));
        $data['show_cur'] = $show_cur;
        $data['per_page'] = $per_page;//每页显示条数
        $data['pageshow'] = $this->pagination->create_links();

        $list = $this->file_model->initFiles('typeid', $where, $like, $config['per_page'], ($page - 1) * $config['per_page']);
        foreach ($list as $k => $v) {
            $user = unserialize($v['add_user']);
            $list[$k]['account'] = $user['account'];
        }
        $data['listss'] = $list;
        $data['filetype'] = $this->file_model->filetypelistByParentid('7');
        $this->load->view('defaults/billmanege', $data);
        $this->load->view('defaults/common/footer');

    }

    /**
     * ajax检查同一个用户下面同分类下面是否有重名的文件标题
     */
    public function ajax_ck_title()
    {
        $title = trim($_POST['title']);//文件标题
        $userid = $this->users['id'];//用户id
        $typeid = $_POST['typeid'];//用户id
        if (empty($title) || empty($typeid) || empty($userid)) {
            echo '-1';//返回-1则表示没有结果
            exit;
        }
        $where = array('typeid' => $typeid, 'user_id' => $userid, 'title' => $title);
        $cnt = $this->file_model->countRows('files_mg', $where);
        echo($cnt);//返回条数
        exit;
    }
}